<template>
    <div>
        <h3 align="left">新增采购单</h3>
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-row>
                <el-col :span="8">
                    <div class="grid-content bg-purple">
                        <el-form-item label="采购单号：" prop="ProcurementCode" style=" text-align: left;" label-width="150px">
                            <el-input v-model="form.ProcurementCode"></el-input>
                        </el-form-item>
                        <el-form-item label="供应商编号：" prop="SupplierCode" style=" text-align: left;" label-width="150px">
                            <el-input v-model="form.SupplierCode"></el-input>
                        </el-form-item>
                        <el-form-item label="电话：" prop="Phone" style=" text-align: left;" label-width="150px">
                            <el-input v-model="form.Phone"></el-input>
                        </el-form-item>
                        <el-form-item label="采购员：" prop="MakerName" style=" text-align: left;" label-width="150px">
                            <el-input v-model="form.MakerName"></el-input>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content bg-purple-light">
                        <el-form-item label="单据类型：" prop="DocumentType" style=" text-align: left;">
                            <el-select v-model="form.DocumentType" clearable placeholder="请选择单据类型：" style="width: 365px;">
                                <el-option label="采购收购入库" value="1"></el-option>
                                <el-option label="销售退货入库" value="2"></el-option>
                                <el-option label="生产产品入库" value="3"></el-option>
                                <el-option label="领用退还入库" value="4"></el-option>
                                <el-option label="借货入库" value="5"></el-option>
                                <el-option label="借用还入" value="6"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="客户名称：" prop="ClientName" style=" text-align: left; width: 465px;">
                            <el-input v-model="form.ClientName"></el-input>
                        </el-form-item>
                        <el-form-item label="收货日：" prop="ReceiptTime" style=" text-align: left;">
                            <el-date-picker v-model="form.ReceiptTime" type="datetime" placeholder="选择日期时间"
                                style="width: 365px;">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="采购时间：" prop="MakerTime" style=" text-align: left;">
                            <el-date-picker v-model="form.MakerTime" type="datetime" placeholder="选择日期时间"
                                style="width: 365px;">
                            </el-date-picker>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content bg-purple">
                        <el-form-item label="销售单号：" prop="SaleCode" style=" text-align: left; width: 465px;">
                            <el-autocomplete v-model="form.SaleCode" :fetch-suggestions="querySearch" placeholder="请输入销售单号"
                                style="width: 365px;">
                            </el-autocomplete>
                        </el-form-item>
                        <el-form-item label="联系人：" prop="ContactName" style="width: 465px;">
                            <el-input v-model="form.ContactName"></el-input>
                        </el-form-item>
                        <el-form-item label="备注：" style="width: 465px;">
                            <el-input v-model="form.Remark"></el-input>
                        </el-form-item>

                    </div>
                </el-col>
            </el-row>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">添加</el-button>
                <el-button @click="jump()">返回</el-button>
            </el-form-item>
        </el-form>

        <h3 align="left" style="width: 500px;">产品信息</h3>

        <div align="right">
            <el-button type="primary" @click="open()">选择产品</el-button>
        </div>

        <template>
            <el-table :data="productlist" border style="width: 100%" @selection-change="handleSelectionChange">>
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column prop="productName" label="产品名称">
                </el-table-column>
                <el-table-column prop="productCode" label="产品编码">
                </el-table-column>
                <el-table-column prop="specs" label="规格">
                </el-table-column>
                <el-table-column prop="unit" label="单位">
                </el-table-column>
                <el-table-column prop="price" label="单价">
                    <template slot-scope="scope">
                        <span style="color:#f23e23; size: 12pt;">
                            ¥ {{ scope.row.price.toFixed(2) }}
                        </span>
                    </template>
                </el-table-column>

                <el-table-column prop="buyNumber" label="数量">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.buyNumber" :min="0">
                        </el-input-number>
                    </template>
                </el-table-column>

                <el-table-column prop="sumPrice" label="总价">

                    <template slot-scope="scope">
                        <span style="color:#f23e23; size: 12pt;">
                            ¥ {{ scope.row.sumPrice=(scope.row.price * scope.row.buyNumber).toFixed(4) }}
                        </span>
                    </template>
                </el-table-column>
            </el-table>
        </template>

        <el-dialog title="提示" :visible.sync="dialogVisible" width="60%">
            产品编号:<el-input v-model="ProductCode" style="width: 200px"></el-input>
            产品名称:<el-input v-model="ProductName" style="width: 200px"></el-input>
            <el-button type="primary" @click="ProductManagementGetList()">查询</el-button>
            <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
                @selection-change="handleSelectionChange1">
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column prop="productCode" label="产品编号"> </el-table-column>
                <el-table-column prop="productName" label="产品名称"> </el-table-column>
                <el-table-column prop="specs" label="规格"> </el-table-column>
                <el-table-column prop="productTypeId" label="类别">

                    <template slot-scope="data">
                        <span v-if="data.row.productTypeId == 1">移动电源</span>
                        <span v-if="data.row.productTypeId == 2">线材类</span>
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="存储单位"> </el-table-column>
                <el-table-column prop="packageType" label="包装类型"> </el-table-column>
                <el-table-column prop="price" label="价格">
                    <template slot-scope="scope">
                        <span style="color:#f23e23; size: 12pt;">
                            ¥ {{ scope.row.price.toFixed(2) }}
                        </span>
                    </template>
                </el-table-column>
            </el-table>
            <br>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageIndex"
                :page-sizes="[2, 3, 6, 10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount">
            </el-pagination>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="off()">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { AddProcureMentAPI, GetSalesCodeListAPI, GetSalesManagementByCodeAPI } from "@/api/BusinessServers/ProcureMent";
import { ProductManagementGetList } from "@/api/BasicsDatumServer/ProductManagement";
import { autoGenerateCode } from "@/utils/utils";
const signalR = require("@microsoft/signalr");
export default {
    data() {
        return {
            //表单数据
            form: {
                Phone: "",
                shoppingList: []
            },
            //表单验证规则
            rules: {
                ReceiptTime: [
                    { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
                ],
                MakerTime: [
                    { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
                ],
                Phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
                ],
                MakerName: [
                    { required: true, message: '请输入采购员', trigger: 'blur' },
                ],
                ProcurementCode: [
                    { required: true, message: '请输入采购单号', trigger: 'blur' },
                ],
                SupplierCode: [
                    { required: true, message: '请输入供应商编号', trigger: 'blur' },
                ],
                ClientName: [
                    { required: true, message: '请输入客户名称', trigger: 'blur' },
                ],
                SaleCode: [
                    { required: true, message: '请输入销售单号', trigger: 'blur' },
                ],
                ContactName: [
                    { required: true, message: '请输入联系人', trigger: 'blur' },
                ],
                DocumentType: [
                    { required: true, message: '请选择单据类型', trigger: 'change' }
                ],

            },
            //多选框选中的数据
            multipleSelection: [],
            multipleSelection1: [],
            //销售信息
            Sales: [],
            //弹出框显示与隐藏
            dialogVisible: false,

            //下拉框选项
            options: [],
            //产品列表
            productlist: [],
            //产品信息
            tableData: [],
            ProductCode: "",
            ProductName: "",
            ProductTypeId: 0,
            //分页信息
            pageIndex: 1,
            pageSize: 2,
            totalCount: 0,
            pageCount: 0,
        }
    },
    watch: {
        //监听销售单号变化
        'form.SaleCode': function (newVal, oldVal) {
            this.GetSalesManagementByCode();
        }
    },
    methods: {

        //多选状态改变时触发
        handleSelectionChange(val) {
            // 设置多选状态
            this.multipleSelection = val;
        },
        //多选状态改变时触发
        handleSelectionChange1(val) {
            // 设置多选状态
            this.multipleSelection1 = val;
        },
        //跳转到列表页
        jump() {
            //跳转到列表页
            this.$router.push({ path: 'ProcureMentList' });
        },
        //提交表单
        submitForm(formName) {

            // 校验表单
            this.$refs[formName].validate((valid) => {

                if (this.multipleSelection.length == 0) {
                    this.$message.error("请选择产品");
                    return;
                }
                if (valid) {
                    let params = {
                        ProcurementCode: this.form.ProcurementCode,
                        DocumentType: this.form.DocumentType,
                        DocumentState: 0,
                        SaleCode: this.form.SaleCode,
                        SupplierCode: this.form.SupplierCode,
                        ClientName: this.form.ClientName,
                        ContactName: this.form.ContactName,
                        Phone: this.form.Phone,
                        ReceiptTime: this.form.ReceiptTime,
                        MakerName: this.form.MakerName,
                        MakerTime: this.form.MakerTime,
                        ProcurementProcurement: true,
                        IsReFund: true,
                        ProcurementState: 0,
                        Remark: this.form.Remark,
                        ProcurementTime: this.form.MakerTime,
                        ShoppingList: this.multipleSelection
                    }
                    // 调用添加接口
                    AddProcureMentAPI(params).then(
                        (res) => {
                            this.receiveMessage();
                            // 判断接口返回状态
                            if (res.data.code == 0) {
                                // 添加成功
                                this.$message.success("添加成功");
                                this.$router.push("ProcureMentList");
                            } else {
                                // 添加失败
                                this.$message.error("添加失败");
                            }
                        }
                    )
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //重置表单
        resetForm(formName) {
            // 重置表单
            this.$refs[formName].resetFields();
            //清空表单
            this.form = {};
            this.form.ProcurementCode = autoGenerateCode("CG");
        },
        //绑定销售编号
        BindSalesList() {
            GetSalesCodeListAPI().then(res => {
                this.options = Array.from(res.data.data, item => ({ value: item.salesCode }));
            });
        },
        //联想输入
        querySearch(queryString, cb) {
            var options = this.options;
            var results = queryString ? options.filter(this.createFilter(queryString)) : options;
            cb(results);
        },
        createFilter(queryString) {
            // 返回一个函数，该函数接受一个参数option，用于判断option的值是否以queryString开头
            return (option) => {
                // 返回一个布尔值，表示option的值是否以queryString开头
                return (option.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        //获取销售单信息
        GetSalesManagementByCode() {
            let params = {
                code: this.form.SaleCode
            }
            GetSalesManagementByCodeAPI(params).then(res => {
                if (res.data.data == null) {
                    return;
                }
                this.form.Phone = res.data.data.phone;
                this.form.DocumentType = res.data.data.documentType;
                this.form.SupplierCode = res.data.data.supplierCode;
                this.form.ClientName = res.data.data.clientName;
                this.form.ContactName = res.data.data.creator;
            });
        },
        //打开对话框
        open() {
            this.dialogVisible = true;
        },
        //获取产品信息列表
        ProductManagementGetList() {
            var params = {
                ProductCode: this.ProductCode,
                ProductName: this.ProductName,
                ProductTypeId: this.ProductTypeId,
                pageIndex: this.pageIndex,
                pageSize: this.pageSize,
            };
            ProductManagementGetList(params).then((res) => {
                this.tableData = res.data.data.result;
                this.totalCount = res.data.data.totalCount;
                this.pageCount = res.data.data.pageCount;
            });
        },
        //每页大小改变时触发
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.ProductManagementGetList();
        },
        //当前页改变时触发
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.pageIndex = val;
            this.ProductManagementGetList();
        },
        //关闭对话框
        off() {
            this.dialogVisible = false;
            this.productlist = this.multipleSelection1;
        },
        initsignalr() {
            // 建立连接
            this.connection = new signalR.HubConnectionBuilder()
                .withUrl("http://localhost:63626/chatHub")
                .withAutomaticReconnect()
                .build();

            // 注册方法
            this.connection.on("ShowMsg", this.ShowMsg);

            // 开始连接
            this.connection
                .start()
                .then(() => console.log("Connected!"))
                .catch((err) => {
                    console.log(err);
                });
        },
        ShowMsg(msgInfo) {
            console.log(11, msgInfo);
            this.msgs.push(msgInfo + "--" + (this.msgs.length + 1));
        },
        // 调用后端方法
        receiveMessage() {
            this.$store.state.snm++;
            let params = "Hello";
            this.connection
                .invoke("SendMessage", params)
                .then(() => console.log("send succeed!"));
        },
    },
    created() {
        //调用绑定销售列表函数
        this.BindSalesList();
        //调用自动生成代码函数，生成采购代码
        this.form.ProcurementCode = autoGenerateCode("CG");
        //调用产品管理获取列表函数
        this.ProductManagementGetList();

        this.initsignalr();
    },
}
</script>

<style></style>